package com.notary.data.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.notary.data.bean.*;
import com.notary.data.request.ContractVO;
import com.notary.data.request.OfficeOrderRequest;
import com.notary.data.request.SyncDataRequest;
import com.notary.data.service.OfficeRequestService;
import com.notary.entity.*;
import com.notary.entity.vo.JsonResult;
import com.notary.mapper.*;
import com.notary.service.NotaryDocumentService;
import com.notary.service.NotaryItemService;
import com.notary.service.NotaryOrgService;
import com.notary.util.DesEncryptFile;
import com.notary.util.DesUtil;
import com.notary.util.HttpUtils;
import io.netty.util.internal.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.quartz.DisallowConcurrentExecution;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.GeneralSecurityException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Service
@Slf4j
public class OfficeRequestServiceImpl implements OfficeRequestService {

    @Autowired
    DesEncryptFile desEncryptFile;

    @Autowired
    RedisTemplate redisTemplate;

    @Resource
    ContractMapper contractMapper;

    @Resource
    CompanyMapper companyMapper;

    @Resource
    PersonMapper personMapper;

    @Resource
    ContractCurrentStatusMapper contractCurrentStatusMapper;

    @Resource
    NotaryDocumentMapper notaryDocumentMapper;
    @Resource
    NotaryItemMapper notaryItemMapper;

    @Resource
    NotaryMapper notaryMapper;
    @Resource
    NotaryPurposeMapper notaryPurposeMapper;
    @Autowired
    NotaryOrgService notaryOrgService;
    @Autowired
    NotaryItemService notaryItemService;


    @Value("${office.deskey}")
    private String deskey;

    @Autowired
    private OSS ossClient;

    @Value("${aliyun.bucketName}")
    private String bucketName;

    @Value("${aliyun.urlPrefix}")
    private String urlPrefix;

    @Value("${aliyun.folderName}")
    private String folderName;

    @Override
    public JSONObject checkToken(JSONObject data) {
        //{
        //"status": 0,
        //"info": "校验服务器成功！！！",
        //"data": "welcome to Sanxia Notarization System"
        //}
        JSONObject result = new JSONObject();
        return result;
    }


    protected String encrypt(String desKey, JSONObject data) throws Exception {
        String desIv = RandomUtil.randomNumbers(8);
        String dataStr = DesUtil.encode(desKey, desIv, data.toJSONString());
        JSONObject body = new JSONObject();
        body.put("data", dataStr);
        body.put("timestamp", desIv);
        return body.toJSONString();
    }


    protected JSONObject parseObject(String desKey, String result) {
        try {
            JSONObject encode = JSONObject.parseObject(result);
            if (encode.get("status") != null) {
                return encode;
            }
            String decode = DesUtil.decode(desKey, encode.getString("timestamp"), encode.getString("data"));
            return JSONObject.parseObject(decode);
        } catch (Exception e) {
            log.error("获取公证信息失败{}", e.getMessage());
            return null;
        }
    }

    protected JSONArray parseArray(String desKey, String result) {
        try {
            JSONObject encode = JSONObject.parseObject(result);
            String decode = DesUtil.decode(desKey, encode.getString("timestamp"), encode.getString("data"));
            return JSONArray.parseArray(decode);
        } catch (Exception e) {
            log.error("获取公证信息失败{}", e.getMessage());
            return null;
        }
    }

    //根据卷宗号查询公证数据信息
    @Override
    public JSONObject queryNotaryByTransNo(JSONObject data) throws Exception {
        String result = DesUtil.decode(deskey, data.getString("timestamp"), data.getString("data"));
        JSONObject params = JSONObject.parseObject(result);
        String transNo = params.getString("transNo");
        Contract contract = contractMapper.selectOne(new QueryWrapper<Contract>().eq("trans_no", transNo));
        JSONObject jsonResult = new JSONObject();
        JSONObject data1 = new JSONObject();
        if (contract == null) {
            jsonResult.put("status", false);
            jsonResult.put("msg", "卷宗号不存在!");
        } else {
            data1.put("gzno", contract.getGzNo());
            data1.put("notarNo", contract.getNotaryNo());
            jsonResult.put("data", data1);
            jsonResult.put("status", true);
            jsonResult.put("msg", "卷宗号已存在!");
        }
        String timestamp = System.currentTimeMillis() / 100000 + "";
        JSONObject jsonData = new JSONObject();
        jsonData.put("timestamp", timestamp);
        jsonData.put("data", DesUtil.encode(deskey, timestamp, jsonResult.toJSONString()));
        return jsonData;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JSONObject getOrderInfo(JSONObject data) throws Exception {
        String result = DesUtil.decode(deskey, data.getString("timestamp"), data.getString("data"));
        log.info("result:{}", result);
        OfficeOrderRequest request = JSONUtil.toBean(result, OfficeOrderRequest.class);
        String transNo = request.getTransNo();
        Contract contractEntity = contractMapper.selectOne(new QueryWrapper<Contract>().eq("trans_no", transNo));
        if (contractEntity != null) {
            Map<String, Object> msg = new HashMap<>();
            msg.put("transNo", request.getTransNo());
            msg.put("notarNo", contractEntity.getNotaryNo());
            JSONObject returnMsg = new JSONObject();
            returnMsg.put("data", msg);
            returnMsg.put("msg", "数据已存在");
            returnMsg.put("status", true);
            JSONObject returnData = new JSONObject();
            returnData.put("timestamp", data.getString("timestamp"));
            returnData.put("data", DesUtil.encode(deskey, data.getString("timestamp"), returnMsg.toJSONString()));
            return returnData;
        }
        //默认10 公证类型 借款合同
        Integer notaryType = request.getNotarytype();
        //公证类别未传
        NotaryItemVO notaryItemVO = request.getNotaryItems().get(0);
        //创建案件
        Contract entity = new Contract();
        String gzNo = UUID.randomUUID().toString().replaceAll("-", "");
        entity.setGzNo(gzNo);
        entity.setOrgno(request.getOrgno());
        entity.setOrg(request.getOrg());
        entity.setLx(notaryType.toString());
        entity.setStatus(request.getStatus());
        if (request.getSlsj() != null) {
            entity.setAcceptDate(DateUtil.parseDate(request.getSlsj()));
        }

        entity.setNotaryNo(getNotaryNo());
        entity.setFs(notaryItemVO.getFs());
        QueryWrapper<NotaryItem> itemQueryWrapper = new QueryWrapper<>();
        itemQueryWrapper.eq("name", notaryItemVO.getItemName());
        NotaryItem notaryItem = notaryItemService.getOne(itemQueryWrapper);
        entity.setNotaryItem(notaryItem.getId());
        entity.setYt("72");
        BigDecimal charge = new BigDecimal(request.getCharge());
        entity.setCharge(charge); //用分做单位
        entity.setTransNo(request.getTransNo());
        entity.setDataType("1");
        if (!StringUtil.isNullOrEmpty(request.getGzs())) {
            entity.setStatus(7);
            entity.setIssuingTime(new SimpleDateFormat("yyyy-MM-dd").parse(request.getCzsj()));
        } else {
            entity.setStatus(1);
        }
        entity.setNotaryId(request.getNotaryId());
        entity.setNotaryName(request.getNotaryName());
        contractMapper.insert(entity);
        Long contractId = entity.getId();
        Items items = request.getItems();
        List<PersonVO> personList = items.getPersons();
        for (PersonVO person : personList) {
            String isPersonOrCompany = person.getIsPersonOrCompany();
            if (Objects.equals(isPersonOrCompany, "个人")) {
                Personal p = person.getPersonnal();
                Person per = new Person();
                per.setContractId(contractId);
                per.setName(p.getName());
                per.setSex(Objects.toString(p.getXinbie()));
                per.setBirth(p.getBirth());
                per.setIdCard(p.getCard());
                per.setFrontCard(p.getFrongcard());
                per.setBackCard(p.getAftercard());
                per.setMergeCard(p.getMerge());
                per.setPhone(p.getPhone());
                per.setAddress(p.getAddress());
                per.setEmail(p.getEmail());
                per.setCreateTime(new Date());
                personMapper.insert(per);
            } else if (Objects.equals(isPersonOrCompany, "企业")) {
                CompanyVO p = person.getCompany();
                Company company = new Company();
                company.setContractId(entity.getId());
                company.setCompanyName(p.getQiyemingcheng());
                company.setCreditCode(p.getCard());
                company.setBusinessLicense(p.getCardpic());
                company.setLegalName(p.getLegalname());
                company.setLegalCard(p.getLegalcard());
                company.setDailiname(p.getDailiname());
                company.setDailicard(p.getDailicard());
                company.setPhone(p.getPhone());
                company.setEmail(p.getEmail());
                company.setAddress(p.getQiyeaddress());
                String fujianList = p.getFujian();
                if (!StringUtils.isEmpty(fujianList)) {
                    company.setLicenseFile(fujianList);
                }
                company.setCreateTime(new Date());
                companyMapper.insert(company);
            }
        }

        String contract = items.getContract();
        if (StringUtils.isNoneBlank(contract)) {//被公证合同
            NotaryDocument document = new NotaryDocument();
            document.setContractId(contractId);
            document.setName(contract.substring(contract.lastIndexOf("/") + 1));
            document.setType(0);
            document.setPath(this.uploadUrl(contract));
            document.setCreateTime(new Date());
            notaryDocumentMapper.insert(document);
        }
        NotaryDocumentVO gzcontract = items.getGzcontract();
        String shenqingsheet = gzcontract.getShenqingsheet();
        if (StringUtils.isNoneBlank(shenqingsheet)) {//公证申请书
            NotaryDocument document = new NotaryDocument();
            document.setContractId(contractId);
            document.setName(shenqingsheet.substring(shenqingsheet.lastIndexOf("/") + 1));
            document.setType(1);
            document.setPath(this.uploadUrl(shenqingsheet));
            document.setCreateTime(new Date());
            notaryDocumentMapper.insert(document);
        }

        String gaozhisheet = gzcontract.getGaozhisheet();
        if (StringUtils.isNoneBlank(gaozhisheet)) {//公证告知书
            NotaryDocument document = new NotaryDocument();
            document.setContractId(contractId);
            document.setName(gaozhisheet.substring(gaozhisheet.lastIndexOf("/") + 1));
            document.setType(2);
            document.setPath(this.uploadUrl(gaozhisheet));
            document.setCreateTime(new Date());
            notaryDocumentMapper.insert(document);
        }

        String shoulisheet = gzcontract.getShoulisheet();
        if (StringUtils.isNoneBlank(shoulisheet)) {//受理通知书
            NotaryDocument document = new NotaryDocument();
            document.setContractId(contractId);
            document.setName(shoulisheet.substring(shoulisheet.lastIndexOf("/") + 1));
            document.setType(3);
            document.setPath(this.uploadUrl(shoulisheet));
            document.setCreateTime(new Date());
            notaryDocumentMapper.insert(document);
        }

        String gzbilu = gzcontract.getGzbilu();
        if (StringUtils.isNoneBlank(gzbilu)) {//公证笔录
            NotaryDocument document = new NotaryDocument();
            document.setContractId(contractId);
            document.setName(gzbilu.substring(gzbilu.lastIndexOf("/") + 1));
            document.setType(4);
            document.setPath(this.uploadUrl(gzbilu));
            document.setCreateTime(new Date());
            notaryDocumentMapper.insert(document);
        }

        String zhuanrangsheet = gzcontract.getZhuanrangsheet();
        if (StringUtils.isNoneBlank(zhuanrangsheet)) {//合同转让书
            NotaryDocument document = new NotaryDocument();
            document.setContractId(contractId);
            document.setName(zhuanrangsheet.substring(zhuanrangsheet.lastIndexOf("/") + 1));
            document.setType(7);
            document.setPath(this.uploadUrl(zhuanrangsheet));
            document.setCreateTime(new Date());
            notaryDocumentMapper.insert(document);
        }


        List<String> videos = items.getVideo();
        for (String video : videos) {//视频
            NotaryDocument document = new NotaryDocument();
            document.setContractId(contractId);
            String path = Objects.toString(video);
            document.setName(video.substring(video.lastIndexOf("/") + 1));
            document.setType(6);
            document.setPath(this.uploadUrl(path));
            document.setCreateTime(new Date());
            notaryDocumentMapper.insert(document);
        }

//        String fujian = items.getFujian();
//        if (StringUtils.isNoneBlank(fujian)) {//附件
//            NotaryDocument document = new NotaryDocument();
//            document.setContractId(contractId);
//            document.setName(fujian.substring(fujian.lastIndexOf("/") + 1));
//            document.setType(5);
//            document.setPath(fujian);
//            document.setCreateTime(new Date());
//            notaryDocumentMapper.insert(document);
//        }

        ContractCurrentStatus contractCurrentStatus = new ContractCurrentStatus();
        contractCurrentStatus.setContractId(contractId);
        contractCurrentStatus.setStatus(1);
        contractCurrentStatus.setOwner(request.getNotaryId());
        contractCurrentStatusMapper.insert(contractCurrentStatus);

        Map<String, Object> msg = new HashMap<>();
        msg.put("transNo", request.getTransNo());
        msg.put("notarNo", entity.getNotaryNo());
        msg.put("gzNo", gzNo);
        JSONObject returnMsg = new JSONObject();
        returnMsg.put("data", msg);
        returnMsg.put("msg", "数据传输成功");
        returnMsg.put("status", true);
        JSONObject returnData = new JSONObject();
        returnData.put("timestamp", data.getString("timestamp"));
        returnData.put("data", DesUtil.encode(deskey, data.getString("timestamp"), returnMsg.toJSONString()));
        return returnData;
    }

    //根据卷宗号查询公证数据信息
    //{"data":{"bzzt":"受理","cbgzybh":"370828db6396a324016396f5c2b10003","cbgzyxm":"严继宁","getfile":"","jgbh":"fqpdsgzc56c071e30156c081d21f0002","jgmc":"湖北省宜昌市三峡公证处","lxdh":"","notarNo":"2020002514","slsj":"2020年07月05日"},"msg":"","status":"0"}
    @Override
    public JSONObject getNotaryInfo(JSONObject data) throws Exception {
        String result = DesUtil.decode(deskey, data.getString("timestamp"), data.getString("data"));
        log.info("result:{}", result);
        JSONObject params = JSONObject.parseObject(result);
        log.info("params:{}", params);
        String notaryNo = params.getString("notaryNo");
        Map<String, Object> map = contractMapper.getNotaryInfo(notaryNo);
        Long contractId = (Long) map.get("id");

        QueryWrapper<NotaryDocument> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("contract_id", contractId);
        queryWrapper.eq("type", 11);
        NotaryDocument zxMap = notaryDocumentMapper.selectOne(queryWrapper);

        map.put("zxzsUrl", zxMap == null ? null : zxMap.getPath());
        Map<String, Object> returnMap = new HashMap<>();
        returnMap.put("data", map);
        returnMap.put("msg", "查询成功");
        returnMap.put("status", "0");
        String timestamp = System.currentTimeMillis() / 100000 + "";
        String resultData = DesUtil.encode(deskey, timestamp, JSONArray.toJSONString(returnMap));
        log.info("map:{}", returnMap);
        JSONObject jsonData = new JSONObject();
        jsonData.put("timestamp", timestamp);
        jsonData.put("data", resultData);
        return jsonData;
    }

    //{"data":{"bzzt":"受理","cbgzybh":"370828db6396a324016396f5c2b10003","cbgzyxm":"严继宁","getfile":"","jgbh":"fqpdsgzc56c071e30156c081d21f0002","jgmc":"湖北省宜昌市三峡公证处","lxdh":"","notarNo":"2020002514","slsj":"2020年07月05日"},"msg":"","status":"0"}
    @Override
    public JSONObject callback(String notaryNo) throws Exception {
        Map<String, Object> map = contractMapper.getNotaryInfo(notaryNo);
        String timestamp = System.currentTimeMillis() / 100000 + "";
        String resultData = DesUtil.encode(deskey, timestamp, JSONArray.toJSONString(map));
        JSONObject jsonData = new JSONObject();
        jsonData.put("timestamp", timestamp);
        jsonData.put("data", resultData);
        return jsonData;
    }

    //加密返回公证员数据
    @Override
    public JSONObject getNotaryIdAndName(JSONObject data) throws Exception {
        // String result = DesUtil.decode(deskey, data.getString("timestamp"), data.getString("data"));
        //  JSONObject params = JSONObject.parseObject(result);
        //  String officeId = params.getString("officeId");
        //  List<Map<String, Object>> list = notaryMapper.getMaps(officeId);
        List<Map<String, Object>> list = notaryMapper.getMaps();
        String timestamp = System.currentTimeMillis() / 100000 + "";
        String resultData = DesUtil.encode(deskey, timestamp, JSONArray.toJSONString(list));
        JSONObject jsonData = new JSONObject();
        jsonData.put("timestamp", timestamp);
        jsonData.put("data", resultData);
        return jsonData;
    }

    //加密返回公证用途数据
    @Override
    public JSONObject queryPurpose(JSONObject data) throws Exception {
        //  String result = DesUtil.decode(deskey, data.getString("timestamp"), data.getString("data"));
        //  JSONObject params = JSONObject.parseObject(result);
        //   String officeId = params.getString("officeId");
        //  List<Map<String, Object>> list = notaryPurposeMapper.getMaps(officeId);
        List<Map<String, Object>> list = notaryPurposeMapper.getMaps();
        String timestamp = System.currentTimeMillis() / 100000 + "";
        String resultData = DesUtil.encode(deskey, timestamp, JSONArray.toJSONString(list));
        JSONObject jsonData = new JSONObject();
        jsonData.put("timestamp", timestamp);
        jsonData.put("data", resultData);
        return jsonData;
    }


    //加密返回公证事项数据
    @Override
    public JSONObject queryNotaryItemInfo(JSONObject data) throws Exception {
        // String result = DesUtil.decode(deskey, data.getString("timestamp"), data.getString("data"));
        // JSONObject params = JSONObject.parseObject(result);
        //String officeId = params.getString("officeId");
        //  List<Map<String, Object>> list = notaryItemMapper.getMaps(officeId);
        List<Map<String, Object>> list = notaryItemMapper.getMaps();
        String timestamp = System.currentTimeMillis() / 100000 + "";
        String resultData = DesUtil.encode(deskey, timestamp, JSONArray.toJSONString(list));
        JSONObject jsonData = new JSONObject();
        jsonData.put("timestamp", timestamp);
        jsonData.put("data", resultData);
        return jsonData;
    }

    //加密返回公证书字节或文件流数据
    @Override
    public byte[] querySealNotaryPdf(JSONObject data) throws Exception {
        String result = DesUtil.decode(deskey, data.getString("timestamp"), data.getString("data"));
        JSONObject params = JSONObject.parseObject(result);
        String gzsbh = params.getString("gzsbh");//公证书编号
        String notaryOfficeId = params.getString("notaryOfficeId");//公证处id
        String gzno = params.getString("gzno");
        Contract contract = contractMapper.selectOne(new QueryWrapper<Contract>().eq("certificate_no", gzsbh));
        QueryWrapper<NotaryDocument> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("contract_id", contract.getId());
        queryWrapper.eq("type", 9);
        NotaryDocument notaryDocument = notaryDocumentMapper.selectOne(queryWrapper);
        if (notaryDocument != null) {
            String path = notaryDocument.getPath();
            //从文件链接里获取文件流
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //设置超时间为3秒
            conn.setConnectTimeout(3 * 1000);
            //防止屏蔽程序抓取而返回403错误
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            //得到输入流
            InputStream inputStream = conn.getInputStream();
            return desEncryptFile.encrypt(IoUtil.readBytes(inputStream));
        }
        return new byte[0];
    }

    @Override
    public JSONObject applyExecCert(JSONObject data) throws Exception {
        return null;
    }

    @Override
    public byte[] downloadExecCert(String contractNo, HttpServletResponse response) throws Exception {
        return new byte[0];
    }

    @Override
    public JSONObject getNotaryStatus(JSONObject data) throws Exception {
        JSONObject jsonObject = contractMapper.getNotrayStatus(data.getString("notaryNo"));
        String slsj = jsonObject.getString("slsj");
        String[] a = slsj.split("-");
        slsj = a[0] + "年" + a[1] + "月" + a[2] + "日";
        jsonObject.put("slsj", slsj);
        return jsonObject;
    }

    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class)
    public JSONObject syncData(JSONObject data) throws Exception {
        String result = DesUtil.decode(deskey, data.getString("timestamp"), data.getString("data"));
        SyncDataRequest syncDataRequest = JSONObject.parseObject(result, SyncDataRequest.class);
        ContractVO contractVO = syncDataRequest.getContractVO();
        List<com.notary.data.request.PersonVO> personList = syncDataRequest.getPersonalList();
        List<com.notary.data.request.CompanyVO> companyVOList = syncDataRequest.getCompanyList();
        List<com.notary.data.request.NotaryDocumentVO> documentVOList = syncDataRequest.getNotaryDocumentVOList();
        String notaryNo = contractVO.getNotaryNo();
        Contract contract = contractMapper.selectOne(new QueryWrapper<Contract>().eq("notary_no", notaryNo));
        if (contract != null) {
            contract.setStatus(contractVO.getStatus());
            contract.setCertificateNo(contractVO.getGzsbh());
            contract.setAcceptDate(contractVO.getSlsj());
            contract.setIssueDate(DateUtil.formatDate(contractVO.getCzsj()));
            contract.setNotaryNo(contractVO.getNotaryNo());
            contractMapper.updateById(contract);
        } else {
            contract = new Contract();
            contract.setTransNo(contractVO.getTransNo());
            contract.setNotaryNo(contractVO.getNotaryNo());
            contract.setCertificateNo(contractVO.getGzsbh());
            contract.setAcceptDate(contractVO.getSlsj());
            contract.setNotaryId(contractVO.getNotaryId());
            contract.setNotaryName(contractVO.getNotaryName());
            contract.setIssueDate(DateUtil.formatDate(contractVO.getCzsj()));
            contract.setStatus(contractVO.getStatus());
            contract.setCharge(new BigDecimal(contractVO.getCharge()));
            contract.setFs(contractVO.getFs());
            contract.setNotaryItem(contractVO.getNotaryItem());
            if (contractVO.getCreateTime() != null) {
                contract.setCreateTime(contractVO.getCreateTime());
            }
            contract.setOrg(contractVO.getOrg());
            contract.setOrgno(contractVO.getOrgno());
            contractMapper.insert(contract);
            Long contractId = contract.getId();
            personList.forEach(p -> {
                Person person = new Person();
                BeanUtils.copyProperties(p, person);
                person.setContractId(contractId);
                personMapper.insert(person);
            });
            companyVOList.forEach(c -> {
                Company company = new Company();
                BeanUtils.copyProperties(c, company);
                company.setContractId(contractId);
                companyMapper.insert(company);
            });
            documentVOList.forEach(d -> {
                NotaryDocument document = new NotaryDocument();
                BeanUtils.copyProperties(d, document);
                document.setContractId(contractId);
                notaryDocumentMapper.insert(document);
            });
        }
        Map<String, Object> msg = new HashMap<>();
        msg.put("transNo", contractVO.getTransNo());
        JSONObject returnMsg = new JSONObject();
        returnMsg.put("data", msg);
        returnMsg.put("msg", "数据同步成功");
        returnMsg.put("status", true);
        JSONObject returnData = new JSONObject();
        returnData.put("timestamp", data.getString("timestamp"));
        returnData.put("data", DesUtil.encode(deskey, data.getString("timestamp"), returnMsg.toJSONString()));
        return returnData;
    }

    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class)
    public void dealSyncData(List<SyncDataRequest> syncDataList) throws Exception {
        syncDataList.forEach(syncDataRequest -> {
            ContractVO contractVO = syncDataRequest.getContractVO();
            List<com.notary.data.request.PersonVO> personList = syncDataRequest.getPersonalList();
            List<com.notary.data.request.CompanyVO> companyVOList = syncDataRequest.getCompanyList();
            List<com.notary.data.request.NotaryDocumentVO> documentVOList = syncDataRequest.getNotaryDocumentVOList();
            String notaryNo = contractVO.getNotaryNo();
            if (StringUtils.isBlank(notaryNo)) {
                log.info("同步数据中notaryNo不能为空！");
                return;
            }
            Contract contract = contractMapper.selectOne(new QueryWrapper<Contract>().eq("notary_no", notaryNo));

            if (contract != null) {
                Long contractId = contract.getId();
                contract.setStatus(contractVO.getStatus());
                contract.setCertificateNo(contractVO.getGzsbh());
                contract.setAcceptDate(contractVO.getSlsj());
                if (contractVO.getCzsj() != null) {
                    contract.setIssueDate(DateUtil.formatDate(contractVO.getCzsj()));
                    contract.setIssuingTime(contractVO.getCzsj());
                }
                contract.setNotaryNo(contractVO.getNotaryNo());
                documentVOList.forEach(d -> {
                    if (contractVO.getStatus() > 5 && contractVO.getGzs() != null && !contractVO.getGzs().isEmpty()) {
                        NotaryDocument documentTemp = notaryDocumentMapper.selectOne(new QueryWrapper<NotaryDocument>().eq("file_type", 9).eq("contract_id", contractId));
                        if (documentTemp == null) {
                            NotaryDocument document = new NotaryDocument();
                            BeanUtils.copyProperties(d, document);
                            document.setContractId(contractId);
                            notaryDocumentMapper.insert(document);
                        }
                    }
                });
                log.info("contract更新:" + contract.toString());
                contractMapper.updateById(contract);
            } else {

                log.info("contractVO:" + contractVO);
                contract = new Contract();

                contract.setTransNo(contractVO.getTransNo());

                contract.setNotaryNo(contractVO.getNotaryNo());
                contract.setCertificateNo(contractVO.getGzsbh());
                contract.setAcceptDate(contractVO.getSlsj());
                contract.setNotaryId(contractVO.getNotaryId());
                contract.setNotaryName(contractVO.getNotaryName());

                if (contractVO.getCzsj() != null) {
                    contract.setIssueDate(DateUtil.formatDate(contractVO.getCzsj()));
                    contract.setIssuingTime(contractVO.getCzsj());
                }

                contract.setStatus(contractVO.getStatus());
                contract.setCharge(new BigDecimal(contractVO.getCharge()));
                contract.setFs(contractVO.getFs());
                contract.setNotaryItem(contractVO.getNotaryItem());

                if (contractVO.getCreateTime() != null) {
                    contract.setCreateTime(contractVO.getCreateTime());
                }

                contract.setOrg(contractVO.getOrg());
                contract.setOrgno(contractVO.getOrgno());

                contractMapper.insert(contract);
                Long contractId = contract.getId();

                personList.forEach(p -> {
                    Person person = new Person();
                    BeanUtils.copyProperties(p, person);
                    person.setContractId(contractId);
                    personMapper.insert(person);
                });

                companyVOList.forEach(c -> {
                    Company company = new Company();
                    BeanUtils.copyProperties(c, company);
                    company.setContractId(contractId);
                    companyMapper.insert(company);
                });

                documentVOList.forEach(d -> {
                    NotaryDocument document = new NotaryDocument();
                    BeanUtils.copyProperties(d, document);
                    document.setContractId(contractId);
                    notaryDocumentMapper.insert(document);
                });

                ContractCurrentStatus contractCurrentStatus = new ContractCurrentStatus();
                contractCurrentStatus.setContractId(contractId);
                contractCurrentStatus.setStatus(contractVO.getStatus());
                contractCurrentStatus.setOwner(contractVO.getNotaryId());
                contractCurrentStatusMapper.insert(contractCurrentStatus);
            }
        });
    }

    @Override
    public JsonResult getNotaryOrExecuteHashCode(JSONObject data) {
        String notaryNo = data.getString("notaryNo");
        String hashCode = data.getString("hashCode");
        Integer type = data.getInteger("type");
        if (StringUtils.isAnyBlank(notaryNo, hashCode) || type == null) {
            return JsonResult.fail("存证参数传递不准确！");
        }
        Contract contract = contractMapper.selectOne(new QueryWrapper<Contract>().eq("notary_no", notaryNo));
        if (Objects.isNull(contract)) {
            return JsonResult.fail("办证系统该卷宗不存在！");
        }
        switch (type) {
            case 0:
                //公证书
                contract.setNotarybookHashcode(hashCode);
                break;
            case 1:
                //执行证书
                contract.setExecutebookHashcode(hashCode);
                break;
            default:
                return JsonResult.fail("存证类型传值错误！");
        }
        if (contractMapper.updateById(contract) > 0) {
            return JsonResult.success("办证系统存储哈希值成功！");
        }
        return JsonResult.fail("办证系统存储哈希值失败！");
    }

    private String getNotaryNo() {
        StringBuilder sb = new StringBuilder();
        String date = new SimpleDateFormat("yyyy").format(new Date());
        String key = "REDIS_KEY_PREFIX_NOTARY_NO";
        Long increment = redisTemplate.opsForValue().increment(key, 1);
        sb.append(date);
        String incrementStr = increment.toString();
        if (incrementStr.length() <= 6) {
            sb.append(String.format("%06d", increment));
        } else {
            sb.append(incrementStr);
        }
        return sb.toString();
    }

    public String uploadUrl(String url) {
        if (StringUtils.isNotEmpty(url)) {
            InputStream in = HttpUtils.download(url, null);
            //      url = url.substring(0,url.lastIndexOf("?"));
            String key = folderName + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddhhmmss")) + "/" // 时间戳 文件目录
                    + UUID.randomUUID().toString().replaceAll("-", "") // uuid 生成文件名
                    + url.substring(url.lastIndexOf("/"));
            if (null != in) {
                ossClient.putObject(bucketName, key, in);
            }
            return urlPrefix + key;
        } else {
            return url;
        }

    }


}
